
/***********************面板-start****************************/
var rowData=[];
var valMsgRemoveTime=2000;

var selPointMainId = "";
var selPointMainName = "";

// 添加array的删除方法
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

// 重写map，有序key
function treeMap() {
    this.keys = new Array();
    this.datas = new Map();
    //添加键值对
    this.set = function (key, value) {

        if (this.datas.has(key)) {//如键不存在则身【键】数组添加键名
            this.keys.remove(key);
            this.keys.push(key);
        }else {
            this.keys.push(key);
        }
        this.datas.set(key,value);//给键赋值
    };
    //获取键对应的值
    this.get = function (key) {
        return this.datas.get(key);
    };
    //去除键值，(去除键数据中的键名及对应的值)
    this.remove = function (key) {
        this.keys.remove(key);
        this.datas.delete(key);
    };
    //判断键值元素是否为空
    this.isEmpty = function () {
        return this.keys.length == 0;
    };
    //获取键值元素大小
    this.size = function () {
        return this.keys.length;
    };
    //遍历Map,执行处理函数. 回调函数 function(key,value,index){..}
    this.each = function(fn){
        if(typeof fn != 'function'){
            return;
        }
        var len = this.keys.length;
        for(var i=0;i<len;i++){
            var k = this.keys[i];
            fn(k,this.datas.get(k),i);
        }
    };
}

// 缓存已配置：一级点位的巡检内容
var inspContMap = new treeMap();

//主列表参数面板
var homeThemeGridOpt={
    id:"homeThemeGrid",//渲染对象ID 控件的唯一标识
    //title:"测试wdfGrid",//表格标题名暂时不要使用该属性,因为该实现为完善
    autoWidth:true,//是否自适应宽度,该属性设置时,列的width属性将失效,要让列的width属性生效请关闭该属性并设置colFixed属性为true
    autoHeight:true,
    //colFixed:true,//固定列宽,该属性启动时列width属性有效,autoWidth属性无效
    className:"test",//表格样式类名
    //checkbox:true,//是否显示选中按钮
    isMulitCheck:true,//是否支持多选
    loadMsg:"正在加载数据请稍等",//表格加载显示信息
    rowData:rowData,
    // autoGridHeight:true,
    root:"data",//服务端返回的数据对象名
    url:basePath+"/assocConfig/list",
    param:{},//主题类型1:首页主题
    columns:[
        {
            hidden : false,// 是否隐藏该列
            label : "区域中心",// 显示列名称
            name : "areaId",// 列字段属性名
            width : "60",// 列宽度
            formatter : function(columnValue) {
                return getOptionConstant(areaCenterConstant,columnValue);
            },
        },
        {
            hidden : false,// 是否隐藏该列
            label : "服务区",// 显示列名称
            name : "serviceAreaName",// 列字段属性名
            width : "60",// 列宽度
        },
        {
            hidden : false,// 是否隐藏该列
            label : "属性",// 显示列名称
            name : "direction",// 列字段属性名
            width : "60",// 列宽度
            formatter : function(columnValue) {
                return getOptionConstant(areaDirectionConstant,columnValue);
            },
        },
        {
            hidden : false,// 是否隐藏该列
            label : "报表类型",// 显示列名称
            name : "reportTypeName",// 列字段属性名
            width : "60",// 列宽度
        },
        {
            hidden : false,// 是否隐藏该列
            label : "生效时间",// 显示列名称
            name : "startTime",// 列字段属性名
            width : "50",// 列宽度
        },
        {
            hidden : false,// 是否隐藏该列
            label : "失效时间",// 显示列名称
            name : "endTime",// 列字段属性名
            width : "50",// 列宽度
        },
        {
            hidden : false,// 是否隐藏该列
            label : "巡检内容",// 显示列名称
            name : "name",// 列字段属性名
            width : "40",// 列宽度
            isOrder : true,// 是否排序
            isFmtHtml:true,//格式化是否返回html
            formatter : function(columnValue,rowData){
                var btns=[];
                var chakanBtn=$("<a class='gridview_btn' >查看</a>");

                $(chakanBtn).bind("click", function () {
                    showBounced(2,rowData);
                });
                btns.push(chakanBtn);
                return btns;
            }
        },
        {
            hidden : false,// 是否隐藏该列
            label : "操作",// 显示列名称
            name : "id",// 列字段属性名`
            width : "80",// 列宽度
            isOrder : true,// 是否排序
            isFmtHtml:true,//格式化是否返回html
            formatter : function(columnValue,rowData){
                var btns=[];
                var editBtn = $("<a class='gridedit_btn' style='color:#1e90ff;' >编辑</a>");
                var delBtn = $("<a class='griddel_btn' style='color:red;'>删除</a>");

                $(editBtn).bind("click", function () {
                    showBounced(1,rowData);
                });
                $(delBtn).bind("click", function () {
                    deletepointconfig(rowData.id);
                });

                btns.push(editBtn);
                btns.push(delBtn);
                return btns;
            }
        }
    ],
    event:{
        readyLoad:function(opt,gridObj){//grid数据加载前执行
            $(".panel").css("display","none");

        },
        loaded: function (opt, gridObj,rowDatas) {//grid数据加载完成后执行
        },
        restGridHeight:function(gridHeight,gridObj){
            return gridHeight-$("#searchForm").height();
        },
        onRowMouse:function (rowData,gridObj) {
            return [];
        },
    }
};


//关闭弹框
function closePannel(){
    $(".assocconfigPannel").css("display","none");
}


//显示弹框面板
function showBounced(status,rowData){

    // 启用下拉列表
    $("#exeDivFoot").show();

    // 清空缓存数据
    inspContMap = new treeMap();

    if(status==1){

        $("#assocconfigPannel_assocConfigId").val(rowData.id);

        //加载弹框编辑数据
        initServiceAreaIdSelectList(rowData.areaId,rowData.areaDeptId,rowData.serviceAreaId,rowData.reportTypeId);
        loadBouncedData(rowData.id);

    }if (status==2)  {

        $("#assocconfigPannel_assocConfigId").val(rowData.id);

        //加载弹框查看数据
        initServiceAreaIdSelectList(rowData.areaId,rowData.areaDeptId,rowData.serviceAreaId,rowData.reportTypeId);
        loadBouncedData(rowData.id);

        //禁用下拉列表
        $("#exeDivFoot").hide();


    }if (status==3) {

        $("#assocconfigPannel_assocConfigId").val("");

        initServiceAreaIdSelectList("","","","");
        initLiPointMainAddList();
        initConfiguredAddList();
    }

    $(".assocconfigPannel").css("display","block");
}


//删除
function deletepointconfig(id){

    layerConfirm("你确定要删除吗?",function () {
        $.wdfProgress.progress("请稍等...",$("body"));
        $.ajax({
            url:basePath+"/assocConfig/delete",
            data:{
                id:id,
            },
            dataType:"json",
            type: "post",
            contentType:"application/x-www-form-urlencoded",
            beforeSend:null,
            success:function(data){

                $.wdfProgress.showMsg(data.msg,$("body"),true,function(eventObj){

                });

                if (data.status==1){
                    homeThemeGridOpt.keepPage = true;
                    $("#homeThemeGrid").wdfGrid("reload",homeThemeGridOpt);
                }
            },
            error:function (XMLHttpRequest, textStatus, errorThrown) {
                $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
            }
        });
    });
}





/***********************面板-end****************************/

/***********************通用下拉列表-start****************************/



// 初始化加载服务中心名称下拉列表
function initServiceAreaIdSelectList(id,serviceDeptId,serviceAreaId,reportId){
    $("#assocconfigPannel_areaId").html("");

    html="<option value='' ";
    if(id==""){
        html+=" selected='selected' ";
    }
    html+=">请选择服务区</option>";

    html+="<option  value='3'";
    if(id==3){

        html+=" selected='selected'";
    }
    html+=">东部区域中心</option>";

    html+="<option value='4' ";
    if(id==4){

        html+=" selected='selected'";
    }
    html+=">西部区域中心</option>";


    html+="<option value='5' ";
    if(id==5){

        html+=" selected='selected'";
    }
    html+=">南部区域中心</option>";

    html+="<option value='6' ";
    if(id==6){

        html+=" selected='selected'";
    }
    html+=">北部区域中心</option>";

    $("#assocconfigPannel_areaId").html(html);

    //加载点击事件
    $("#assocconfigPannel_areaId").on("change",function () {
        var selVal = $(this).find('option:selected').val();
        initServiceAreaNameSelectList(selVal,'','','');
    });

    initServiceAreaNameSelectList(id,serviceDeptId,serviceAreaId,reportId);
}


// 初始化加载服务区名称下拉列表
function initServiceAreaNameSelectList(parentIDS,id,propId,reportId){

    $("#assocconfigPannel_serviceAreaId").html("");
    var param={type:3,parentIDS:parentIDS};
    $.post(basePath+"/department/listByCondition",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            html="<option value='' ";
            if(id==""){
                html=html+" selected='selected' ";
            }
            html=html+">请选择服务区</option>";
            $(datas).each(function(i,data){
                html=html+"<option value='"+data.id+","+data.pid+"'";
                if(id==data.id){

                    html=html+" selected='selected'";
                }
                html=html+">"+data.name+"</option>";
            });
            $("#assocconfigPannel_serviceAreaId").html(html);

            //加载点击事件
            $("#assocconfigPannel_serviceAreaId").on("change",function () {
                var selVal = $(this).find('option:selected').val().split(',');

                initServiceAreaIdSelectList(selVal[1],selVal[0],'','');
            });

            initServiceAreaPropertySelectList(id,propId,reportId);
        }else {
            alert(data.msg);
        }
    });
}



// 初始化加载服务区属性下拉列表
function initServiceAreaPropertySelectList(areaDeptId,id,reportId){

    $("#assocconfigPannel_serviceAreaDetailId").html("");
    var param={areaDeptId:areaDeptId==""?-1:areaDeptId};
    $.post(basePath+"/serviceArea/list",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            var html="<option value='' ";
            if(id==""){
                html=html+" selected='selected' ";
            }
            html=html+">请选择属性</option>";
            $(datas).each(function(i,data){
                html=html+"<option value='"+data.id+"'";
                if(id==data.id){

                    html=html+" selected='selected'";
                }
                html=html+">"+getOptionConstant(areaDirectionConstant,data.direction)+"</option>";
            });
            $("#assocconfigPannel_serviceAreaDetailId").html(html);

            if(reportId){
                initPlanReportSelectList(reportId);
            }

        }else {
            alert(data.msg);
        }
    });
}

// 初始化加载服务区计划报表下拉列表
function initPlanReportSelectList(id){
    $("#assocconfigPannel_reportId").html("");
    var param={};
    $.post(basePath+"/reporttab/list",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            var html="<option value='' ";
            if(id==""){
                html=html+" selected='selected' ";
            }
            html=html+">请选择报表</option>";
            $(datas).each(function(i,data){
                html=html+"<option value='"+data.id+"'";
                if(id==data.id){

                    html=html+" selected='selected'";
                }
                html=html+">"+data.name+"</option>";
            });
            $("#assocconfigPannel_reportId").html(html);
        }else {
            alert(data.msg);
        }
    });
}


// 下列表选中事件
function selectChange(){
    var selectVal = $("#pointconfig_name_select option:selected").val();
    var selectArr = selectVal.split( ',' );
    if(selectArr.length>1){
        $("#pointconfig_areaId_pannel").val(selectArr[1]);
        $("#pointconfig_areaName_pannel").val(getOptionConstant(areaCenterConstant,selectArr[1]));
    }
}



// 初始化加载左侧栏-区域中心+服务区
function initServiceAreaList(){
    var regionCenterEast = "";
    var regionCenterWest = "";
    var regionCenterSouth = "";
    var regionCenterNorth = "";

    var param={type:3,name:$("#pointconfig_serviceDeptName_LeftSearchPanel").val()};
    $.post(basePath+"/department/listByCondition",param,function(data){
        if (data.status == 1) {
            var datas = data.data;

            $(datas).each(function(i,data){
                var html = "<li><div class=\"pcf_ul_content-dot\"></div><a onclick=\"javascript:pointMainSearch('"+data.id+"',this);\">"+data.name+"</a></li>";

                if(data.pid == 3){

                    regionCenterEast += html;
                }else if (data.pid == 4){

                    regionCenterWest += html;
                }else if(data.pid == 5){

                    regionCenterSouth += html;
                }else if(data.pid == 6){

                    regionCenterNorth += html;
                }
            });
            $("#region_center_east").html(regionCenterEast);
            $("#region_center_west").html(regionCenterWest);
            $("#region_center_south").html(regionCenterSouth);
            $("#region_center_north").html(regionCenterNorth);
        }else {
            alert(data.msg);
        }
    });
}


// 加载右侧搜索栏
function initPlanReportSelectSearchPanel(){
    $("#assocconfigPannel_reportTypeId_SearchPanel").html("");
    var param={};
    $.post(basePath+"/reporttab/list",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            var html="<option value='' selected='selected'>请选择报表类型</option>";
            $(datas).each(function(i,data){
                html+="<option value='"+data.id+"'>"+data.name+"</option>";
            });
            $("#assocconfigPannel_reportTypeId_SearchPanel").html(html);
        }else {
            alert(data.msg);
        }
    });
}





/*######### 关于弹框逻辑 --start #########*/

// 加载弹框一级点位名称
function initLiPointMainAddList(){
    $("#afc_left_content_left").html("");
    var param={};
    $.post(basePath+"/pointMain/list",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            var html="<ul>";
            $(datas).each(function(i,data){
                html+="<li style='padding: 10px 0px 2px 0px'><div style='width: 12px;height: 12px;border-radius:2em;margin:0px 10px 0px 30px;background-color: rgb(187,187,187);display: inline-block;'></div><a style='cursor:pointer;";

                if(i==0){
                    html += "color:blue;";
                    selPointMainId = data.id;
                    selPointMainName = data.name;
                }

                html+="' onclick='selectPointMain("+data.id+",\""+data.name+"\",this)'>"+data.name+"</a></li>";
            });
            html+="</ul>";
            $("#afc_left_content_left").html(html);

            if(datas.length>0){
                initInspectionContentList(datas[0].id);
            }

        }else {
            alert(data.msg);
        }
    });
}

// 一级点位选中函数
function selectPointMain(pointMainId,pointMainName,obj) {

    $(obj).parent().siblings().find("a").css("color","black")
    $(obj).css("color","blue");
    initInspectionContentList(pointMainId);

    selPointMainId = pointMainId;
    selPointMainName = pointMainName;
}



// 加载弹框巡检内容
function initInspectionContentList(pointMainId){
    $("#afc_left_content_right").html("");
    var param={pointMainId:pointMainId==""?-1:pointMainId};
    $.post(basePath+"/inspectionContent/list",param,function(data){
        if (data.status == 1) {
            var datas = data.data;
            var html="<ul>";
            $(datas).each(function(i,data){
                html+="<li style='padding: 10px 0px 0px 0px'><a style='margin-left: 20px'>"+data.problemName+"</a><div onclick='selectInspectionContent("+data.id+",\""+data.problemName+"\",this)'  style='width: 19px;height: 19px;border-radius:2em;margin:0px 10px 0px 20px;border:1px solid rgb(187,187,187);display: inline-block; float: right;cursor:pointer;";

                if(inspContMap.get(data.id)!=null){
                    html+="background-color:rgb(0,118,255);";
                }

                html+= "'";

                if(inspContMap.get(data.id)!=null){
                    html+=" value = '1' ";
                }

                html+="></div></li>";
            });
            html+="</ul>";
            $("#afc_left_content_right").html(html);
        }else {
            alert(data.msg);
        }
    });
}

// 巡检内容选中函数
function selectInspectionContent(id,name,obj) {

    // 获取选中状态的一级点位
    if($(obj).css("background-color")=="rgb(0, 118, 255)"){
        $(obj).css("background-color","rgb(255,255,255)");
        inspContMap.remove(id);
    }else {
        $(obj).css("background-color","rgb(0,118,255)");
        inspContMap.set(id,{problemId:id,problemName:name,pointMainId:selPointMainId,pointMainName:selPointMainName});
    }

    // 触发已配置列表
    initConfiguredAddList();
}


// 选中巡检内容，动态已配置列表
function initConfiguredAddList(){
    $("#afc_right_content").html("");

    var stairMap = new Map();

    // 解析一级点位
    inspContMap.each(function(key,val,i){
        stairMap.set(val.pointMainId,val.pointMainName);
    })

    var html="<ul>";

    stairMap.forEach(function(val1,key1){
        html+="<li style='padding: 10px 0px 0px 0px '><div style='width: 12px;height: 12px;border-radius:2em;margin:0px 10px 0px 20px;background-color: rgb(187,187,187);display: inline-block;'></div><text style='font-weight:bold;'>"+val1+"</text>";
        html+="<ul>";

        inspContMap.each(function(key2,val2){

            if(key1==val2.pointMainId){
                html+="<li style='padding: 10px 0px 0px 0px'><div style='width: 8px;height: 8px;border-radius:2em;margin:0px 10px 0px 40px;background-color: rgb(187,187,187);display: inline-block;'></div>"+val2.problemName+"</li>";
            }
        })
        html+="</ul>";
        html+="</li>";
    })

    html+="</ul>";
    $("#afc_right_content").html(html);
}



// 提交弹框表单
function submit(){

    if(!$("#assocconfigPannel_areaId option:selected").val()){
        layerMsg("请选择区域中心！");
        return;
    }


    if(!$("#assocconfigPannel_serviceAreaId option:selected").val()){
        layerMsg("请选择服务区名称！");
        return;
    }

    if(!$("#assocconfigPannel_serviceAreaDetailId option:selected").val()){
        layerMsg("请选择服务区属性！");
        return;
    }

    if(!$("#assocconfigPannel_reportId option:selected").val()){
        layerMsg("请选择报表类型！");
        return;
    }

    if(inspContMap.size()==0){
        layerMsg("请选择点位巡检内容！");
        return;
    }

    var inspObjArr = new Array();
    inspContMap.each(function(key,val){
        inspObjArr.push(val);
    })

    var param={
        assocConfigId:$("#assocconfigPannel_assocConfigId").val(),
        serviceAreaId:$("#assocconfigPannel_serviceAreaDetailId option:selected").val(),
        reportTypeId:$("#assocconfigPannel_reportId option:selected").val(),
        inspObj:JSON.stringify(inspObjArr),
    };

    var url = "";

    if(!$("#assocconfigPannel_assocConfigId").val()){

        url = basePath+"/assocConfig/saveConfig";
    }else {
        url = basePath+"/assocConfig/updateConfig";
    }

    $.post(url,param,function(data){
        if (data.status == 1) {

            homeThemeGridOpt.keepPage = true;
            $("#homeThemeGrid").wdfGrid("reload",homeThemeGridOpt);
            closePannel();
        }else {
            alert(data.msg);
        }
    });
}


//加载弹框数据
function loadBouncedData(assocConfigId){

    $.ajax({
        url:basePath+"/assocConfig/inspConfiglist",
        data:{
            assocConfigId:assocConfigId,
        },
        dataType:"json",
        type: "post",
        contentType:"application/x-www-form-urlencoded",
        beforeSend:null,
        success:function(data){

            if (data.status==1){

                var datas = data.data;
                for(var i=0,j=datas.length;i<j;i++){
                    inspContMap.set(datas[i].problemId,datas[i]);
                }
                // 刷新弹框数据
                initLiPointMainAddList();
                initConfiguredAddList();
            }
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            $.wdfProgress.showMsg("系统错误或网络延迟！",$("body"),true);
        }
    });

};


/***********************通用下拉列表-end****************************/



/***********************业务操作-start****************************/


//验证消息显示
function showMsg(msg,input,obj){
    var msgBar=$("<div class='msgBar'>"+msg+"</div>");
    $(".msgBar").remove();
    obj.append(msgBar);
    msgBar.animate({"opacity":1},500);
    $(input).data("showMsg",msgBar);
    $(input).addClass("error");
};


//条件查询
function pointMainSearch(serviceAreaId,obj) {
    //旧背景选中取消
    $("#ulli-left ul li a").css("color","black")
    //新背景选中
    $(obj).css("color","blue");
    $('#assocconfigPannel_serviceAreaDeptId_SearchPanel').val(serviceAreaId);
    search();
}


//条件查询
function search() {
    homeThemeGridOpt.param=$('#searchForm').serialize();
    $("#homeThemeGrid").wdfGrid("reload",homeThemeGridOpt);
}

//查询重置
function resetSearch() {
    $('#assocconfigPannel_serviceAreaDeptId_SearchPanel').val("");
    $('#searchForm')[0].reset();
    search();
    initServiceAreaList();
}



/***********************业务操作-end****************************/



/***********************页面初始化-start****************************/
$(document).ready(function() {
    homeThemeGridOpt.height = $(document).height() - $('#searchPanel').height()-20;
    $("#homeThemeGrid").wdfGrid("init",homeThemeGridOpt);

    // 加载上侧栏：
    initServiceAreaIdSelectList("","","","");
    initPlanReportSelectList("");

    // 加载左侧栏：区域中心+服务区列表
    initServiceAreaList();

    // 加载右侧搜索栏：报表类型选择列表
    initPlanReportSelectSearchPanel();

    initLiPointMainAddList();


});
/***********************页面初始化-end****************************/